/**
 *
 */
package rgbos.forum.webClient;

import java.util.Map;

import javax.security.auth.login.LoginException;

import rgbos.forum.domain.Auditor;
import rgbos.forum.exceptions.HashException;

import jaxcent.HtmlInputSubmit;
import jaxcent.JaxcentPage;
import jaxcent.Jaxception;


/**
 * @author Ofir Dagan
 *
 */
public class Registration extends JaxcentPage {
	
	private WebClientHandler handler = WebClientHandler.getWebClientHandler();;
	
	private HtmlInputSubmit submitButton = new HtmlInputSubmit(this, "registerButton") {		
		protected void onClick( Map pageData ) {
			String uName = (String) pageData.get("Username");
			String pass1 = (String) pageData.get("Password");
			String pass2 = (String) pageData.get("Password2");
			String email = (String) pageData.get("Email");
			if(uName.length()>10){
				showMessageDialog("User name needs to be 10 chars max");
			}else if(pass1.length()>10){
				showMessageDialog("Password needs to be 10 chars max");
			}else if(!isValidEmailAddress(email)){
				showMessageDialog("The email address is not valid");
			}else if(!pass1.equals(pass2)){
				showMessageDialog("Passwords doesn't match");
			}else if(!handler.isLegal(uName)){
				showMessageDialog("Your usename contains illegal characters. Please remove them and try again");
			}else if(!handler.isLegal(pass1)){
				showMessageDialog("Your password contains illegal characters. Please remove them and try again");
			}
			else{
				try {
					String hashPass = handler.hashString(pass1);
					if(!handler.register(uName,hashPass,email)){
						showMessageDialog("There was a problem with the username, please choose another one and try again");
						return;
					}else{
						showMessageDialog("Success, you can now login as "+uName );
					}
				} 				
				catch (HashException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
				}
				try {
					navigate( "/login.html" );
				}
				catch (Exception e) {
					e.printStackTrace();
				}
		}
	};};

	public Registration(){
		super();
	}

	public  boolean isValidEmailAddress(String aEmailAddress){
	    if (aEmailAddress == null) return false;
	    boolean result = true;
	    String[] tokens = aEmailAddress.split("@");
	     if (aEmailAddress.startsWith(".") || aEmailAddress.startsWith("@") || tokens.length!=2 || tokens[1].startsWith(".") || !tokens[1].contains(".")) {
	        result = false;
	      }
	    return result;
	}

	protected void onLoad() {
		this.setFormSaveEnabled(false);
		try {
			submitButton.setValue("Register");
		} catch (Jaxception e) {
			e.printStackTrace();
		}
	}
}

